package com.kuang.volatile_t;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: juc
 * @description: 不保证原子性
 * @author: 陈恩涛
 * @create: 2021-03-25 15:14
 **/
public class VDemo {

    private static volatile AtomicInteger num = new AtomicInteger(0);

    public static void add() {
        // AtomicInteger 的加一方法， CAS
        num.getAndIncrement();
    }

    public static void main(String[] args) {

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }

        // main,gc
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println(Thread.currentThread().getName() + ": " + num);
    }
}
